﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using OA.Model;
using OA.BLL;
using OA.Common;
using OA.IBLL;

namespace OA.Controllers.System
{
    public class OrganController : BaseController
    {

        public IBaseService<Org_Organ> service = new Org_OrganService();


        //
        // GET: /Organ/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List()
        {
            ViewBag.Title = "组织机构";
            return View();
        }

        #region 加载datagrid列表 + JsonResult InitGrid()
        [HttpPost]
        public JsonResult InitGrid()
        {
            var ParentID = Request["ParentID"];
            var sort = Request["sort"];
            var order = Request["order"];
            var pageNumber = string.IsNullOrWhiteSpace(Request["page"]) ? 0 : int.Parse(Request["page"]);
            var pageSize = string.IsNullOrWhiteSpace(Request["rows"]) ? 0 : int.Parse(Request["rows"]);

            var Search = HttpUtility.UrlDecode(Request["Search"]);
            var FullName = HttpUtility.UrlDecode(Request["FullName"]);
            var Code = HttpUtility.UrlDecode(Request["Code"]);
            var ShortName = HttpUtility.UrlDecode(Request["ShortName"]);
            var TypeID = Request["TypeID"];
            var IsDisable = Request["IsDisable"];


            var total = 0;

            Expression<Func<Org_Organ, bool>> whereLambda = (c => c.DeleteMark == 0 & c.ParentID == ParentID);

            if (!string.IsNullOrWhiteSpace(Search))
            {
                whereLambda = whereLambda.And<Org_Organ>(c => c.FullName.Contains(Search) || c.Code.Contains(Search) || c.ShortName.Contains(Search));
            }

            if (!string.IsNullOrWhiteSpace(FullName))
            {
                whereLambda = whereLambda.And<Org_Organ>(c => c.FullName.Contains(FullName));
            }
            if (!string.IsNullOrWhiteSpace(Code))
            {
                whereLambda = whereLambda.And<Org_Organ>(c => c.Code.Contains(Code));
            }
            if (!string.IsNullOrWhiteSpace(ShortName))
            {
                whereLambda = whereLambda.And<Org_Organ>(c => c.ShortName.Contains(ShortName));
            }
            if (!string.IsNullOrWhiteSpace(TypeID))
            {
                whereLambda = whereLambda.And<Org_Organ>(c => c.TypeID == TypeID);
            }
            if (!string.IsNullOrWhiteSpace(IsDisable))
            {
                whereLambda = whereLambda.And<Org_Organ>(c => c.IsDisable == (IsDisable == "1" ? true : false));
            }

            var pageInfo = service.PageHelper(pageNumber, pageSize, out total, whereLambda, sort, order);


            var rows = pageInfo.Select(a => new
            {
                a.Code,
                a.DeleteMark,
                a.FullName,
                a.ID,
                IsDisable = a.IsDisable == false ? "正常" : a.IsDisable == true ? "停用" : "",
                a.ParentID,
                a.ShortName,
                a.Sort,
                TypeName = a.TypeID.Equals("01") ? "分支机构" : a.TypeID.Equals("04") ? "普通部门" : ""
            });

            JEasyUIJsonHelper.DataGrid dg = new JEasyUIJsonHelper.DataGrid()
            {
                total = total,
                rows = rows
            };

            return Json(json.obj = dg);
        }
        #endregion


        //
        // GET: /Organ/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Organ/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Organ/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Organ/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Organ/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        #region 加载部门树 + ActionResult InitDeptTree()
        /// <summary>
        /// 加载部门树
        /// </summary>
        /// <returns></returns>
        public ActionResult InitDeptTree()
        {
            string ParentID = Request["ParentID"];
            if (string.IsNullOrWhiteSpace(ParentID))
            {
                var treeNode = entity.Sys_UnitInfo.Select(a => new
                {
                    id = "0",
                    text = a.Name,
                    iconCls = "icon-root",
                    state = "closed",
                    attributes = new { URL = "List?ParentID=0" }
                });
                json.rows = treeNode;
            }
            else
            {
                var treeNode = entity.Org_Organ.Where(a => a.DeleteMark == 0 & a.ParentID == ParentID).OrderBy(a => new { a.Sort, a.SortStr }).Select(a => new
                {
                    id = a.ID,
                    text = a.FullName,
                    iconCls = a.TypeID == "01" ? "icon-org" : "icon-dept",
                    state = entity.Org_Organ.Where(b => b.ParentID == a.ID & b.DeleteMark == 0).Count() > 0 ? "closed" : "open",
                    attributes = new { URL = "List?ParentID=" + a.ID }
                });
                json.rows = treeNode;
            }

            json.success = true;
            return Json(json);
        }
        #endregion


        #region 删除组织机构 + ActionResult Delete()
        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <returns>返回执行结果JSON</returns>
        public ActionResult Delete()
        {
            try
            {
                string deleteId = Request["deleteId"];

                foreach (string id in deleteId.Split(','))
                {
                    var entity = service.DoSearch(c => c.ID.Equals(id)).FirstOrDefault();
                    if (entity == null)
                    {
                        json.success = false;
                        json.msg = "不存在对象:【ID=" + id + "】的组织机构";
                        break;
                    }

                    entity.DeleteMark = 1;


                    var resultCount = service.UpdateEntity();

                    if (resultCount > 0)
                    {
                        json.success = true;
                        json.msg = "成功删除" + resultCount + "条记录";
                    }
                }
            }
            catch (Exception ex)
            {
                json.success = false;
                json.msg = ex.Message;
            }
            return Json(json);
        }
        #endregion

    }
}
